module ApplicationHelper
  def active? query, extra = true, classname = 'active'
    active = extra && query.all? { |key, value| params[key] == value || params[key] == value.to_s }
    active ? classname : ''
  end

  def cip_category_treenav tree, options = {}
    nested_cip_category_treenav tree, data: { toggle: 'nav-tree' }, **options
  end

  def superuser?
    request.env.key?('HTTP_SUPERUSER') || params.key?(:superuser)
  end

  private

  def nested_cip_category_treenav tree, options = {}
    content_tag :ul, class: 'nav nav-pills nav-stacked nav-tree', **options do
      tree.map do |category, children|
        next if category.disabled && !superuser?
        content_tag :li, class: active?(category_id: category.id) do
          result = link_to category.title, cip_admin_category_pages_path(category)
          result += nested_cip_category_treenav children if children.any?
          result
        end
      end.join.html_safe
    end
  end
end
